package com.tanhua.dubbo.utils;

import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Sword
 * @Date 2021/4/14 20:47
 * @Version 1.0
 */
@Slf4j
public class DistanceUtil {
    // 椭球的长半轴
    private static double EARTH_RADIUS = 6378.137;

    /**
     * 计算弧度
     */
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过经纬度计算AB两点间的距离
     * A点经度:longitude1、A点纬度:latitude1、
     * B点经度:longitude2、  B点纬度:latitude2
     */
    public static Map<String, Object> getDistance(double userLongitude, double UserLatitude, double toUserLongitude, double toUserLatitude) {
        double radLat1 = rad(UserLatitude);
        double radLat2 = rad(toUserLatitude);
        double a = radLat1 - radLat2;
        double b = rad(userLongitude) - rad(toUserLongitude);
        double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        distance = distance * EARTH_RADIUS;
        Map<String, Object> map = new HashMap<String, Object>();
        BigDecimal decimal = new BigDecimal(distance);
        //结果保留2位小数
        distance = decimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        map.put("units", "km");
        map.put("distance", distance);
        return map;
    }

    public static void main(String[] args) {
        // A点 117.034727 36.665777	B点 117.041006 36.665871
        Map<String, Object> m = DistanceUtil.getDistance(36.665777, 117.034727, 36.665871, 117.041006);
        System.out.println(m);//AB直线700米左右
    }
}
